/***************************************************************
	To be set in specific .js
***************************************************************/
//VARS
var
	v_video_folder,
	pc_type;
/***************************************************************
	END
***************************************************************/
var
STATE_PLAYER=0,
STATE_BROADCASTER=1,
STATE_LOCAL_PLAYER=2,
STATE_BUSQUEDA=3;
STATE_BACKEND=4;

var
INPUT_STATE_IDLE_CLOSE=0,
INPUT_STATE_OPENING=1,
INPUT_STATE_BUFFERING=2,
INPUT_STATE_PLAYING=3,
INPUT_STATE_PAUSED=4,
INPUT_STATE_STOPPING=5,
INPUT_STATE_ERROR=6;

var wBusqueda = false;
var play_list_items = new Array();
var id_incrementer=0;
var goalbit;
var state = -1;
var selected_item = 0;

//data
var channel_id,channel_name,channel_dsc;
var preferencias;

$(document).ready(function(){
	setModal("div_ofende","Porque te ofende el canal?");
	goalbit = getGoalbitPlugin("goalbit");
	if(goalbit==null){
		msg("Hubo un error con el plugin!",'error');
	}else{
		$("#bchannel_name").val(channel_name);
		$("#bchannel_dsc").val(channel_dsc);

		//Player
		init_local_player();
		$(".player-bar button").mousedown(function(){
			$(this).addClass("presed");
		}).mouseup(function(){
			$(this).removeClass("presed");
		});
		//init_broadcaster();
		inpWaterMark("text_busq","Buscar canales");
		//File chooser
		fileChooserManager();

	}
});

//=====================================================================
//	Generales
//=====================================================================

function sendAjax(opts){
	if(opts.data)
		opts.data.pc_type=getPctype();
	else
		opts.data = {pc_type:getPctype()};
	sendPostAjax(opts);
}
function setLayer(bool){
	if(bool)
		$("#tlayer").show();
	else
		$("#tlayer").hide();
}

//Array de selectores de controles
var controls=["#nav li","#text_busq","#btn_player_stop","#btn_player_play",".del_item_playlist","#btn_browse"];
function disableControls(onlyEnaControls){
	$(controls.diff(onlyEnaControls).join(",")).each(function(){
		if(!this.disabled){
			this.disabled = true;
			this.oldOndClick = this.onclick;
			this.onclick = undefined;
		}
	});
}
function disableAllControls(){
	$(controls.join(",")).each(function(){
		if(!this.disabled){
			this.disabled = true;
			this.oldOndClick = this.onclick;
			this.onclick = undefined;
		}
	});
}
function enableControls(){
	$(controls.join(",")).each(function(){
		if(this.disabled){
			this.disabled = false;
			this.onclick = this.oldOndClick;
		}
	});
}


//=====================================================================
//	Plugin
//=====================================================================

function cleanPlayer(){
	if(goalbit.playlist.isPlaying){
		goalbit.playlist.stop();
		enableControls();
	}
	goalbit.playlist.items.clear();
}

function addItemPlayer(mrl){
	goalbit.playlist.add(mrl);
}

function addItemBroadcast(mrl,transcode){
	goalbit.playlist.add(mrl,null,":sout="+transcode)
}

//=====================================================================
//	Manejo de estados
//=====================================================================

function init_player(ch_name){
	if (wBusqueda) end_busqueda();
	if(state != STATE_PLAYER){
		end();
		state = STATE_PLAYER;
		init("Reproductor de Canales","Detenido",ch_name);
		$("#channel_info").show();
	}
}

function init_broadcaster(){
	if (wBusqueda) end_busqueda();

	if(state != STATE_BROADCASTER){
		end();
		state = STATE_BROADCASTER;
		init("Emitir","Detenido","Datos del canal");
		$("#broadcast_info").show();
		$("#li_broadcaster").addClass("current");
		var
		vb = 300,
		ab = 32,
		chunk_size = 65536,
		base_dir = "/tmp",
                tracker_url = "";
		cleanPlayer();
		addItemBroadcast(
			"v4l2://",
			"#transcode{vcodec=theo,vb="+vb+",scale=1,acodec=vorb,ab="+ab+",channels=2}:duplicate{dst=display,dst=qoe_injector_duplicate{dst=std{access=goalbit_broadcaster{piece-len="+chunk_size+",base-dir='"+base_dir+"',tracker-url='"+tracker_url+"',bitrate="+vb+",channel-name='"+channel_id+"'},mux=ogg,dst='"+channel_id+"'}}}"
		);
		goalbit.activateWebBroadcast();
	}
}

function init_local_player(){
    if(play_list_items.length==0){
		cur_folder = preferencias.playlist_path=="" ? get_default_video_folder():preferencias.playlist_path;
    	AddFolderPlayList();
    }
    if (wBusqueda) end_busqueda();
    if(state != STATE_LOCAL_PLAYER){
        end();
        state = STATE_LOCAL_PLAYER;
        $("#slider_container").show();
        $('#slider').slider({range: "min",value: 0,min: 0, max: 1,disabled:true});
        init("Reproductor Local","Detenido","Lista de reproducción");
        $("#playlist").show();
        $("#li_local_player").addClass("current");
        $(".playlist_nav").show();
    }
}

function init_busqueda(){
    buscarCanalesMain(1,1,"");
}

function end_player(){
    $("#channel_info").hide();
}

function end_busqueda(){
    $("#panel_busqueda").hide();
    $("#li_busqueda").removeClass("current");
    wBusqueda = false;
}

function end_local_player(){
    $("#playlist").hide();
    $("#li_local_player").removeClass("current");
    $(".playlist_nav").hide();
    $("#slider_container").hide();
}

function  end_broadcaster(){
    try{
        goalbit.deactivateWebBroadcast();
    }catch(ex){
        msg("Ocurrio un error tratando de detener al broadcaster...",'error');
    }
    $("#broadcast_info").hide();
    $("#li_broadcaster").removeClass("current");
}

function end(){
    switch(state){
        case STATE_PLAYER:
            end_player();
            break;
        case STATE_LOCAL_PLAYER:
            end_local_player();
            break;
        case STATE_BROADCASTER:
            end_broadcaster();
            break;
        case STATE_BACKEND:
            end_backend();
            break;
    }
}

function init(top,bot,side){
    $("#rol_label").text(top);
    $("#state_label").text(bot);
    $("#pl_label").text(side);
}

//=====================================================================
//	Broadcaster
//=====================================================================

function modify_channel(){
	var tname =$("#bchannel_name").val();
	var tdsc =$("#bchannel_dsc").val();
	sendAjax({
		url: "modify_channel/",
		data: {"name":tname,"dsc":tdsc},
		success: function(resp) {
			msg(resp.msg,resp.ok?'info':'error');
		}
	});
}

//=====================================================================
//	Busqueda
//=====================================================================

function buscarCanales2(nro_page,nro_page_ceibal){
	var $txtB = $("#text_busq");
	buscarCanalesMain(nro_page,nro_page_ceibal,($txtB.attr('empty')=='s') ? "":$txtB.val());
}

function buscarCanalesMain(nro_page,nro_page_ceibal,searchTxt){
	var $divb = $("#main_div_busq");
	sendAjax({
		url: "find_channels/",
		data: {"busqueda":searchTxt,"page":nro_page,"page_ceibal":nro_page_ceibal},
		success: function(data) {
			$divb.html(data);
			if(state != STATE_BUSQUEDA){
				var h = $(document).height()-110;
				$("#li_busqueda").addClass("current");
				$divb.css({height:h});
				end();
				state = STATE_BUSQUEDA;
			}
			if(!wBusqueda){
				wBusqueda = true;
				$("#panel_busqueda").show();
				$("#text_busq").focus();
			}
		}
	});
}

function buscarCanalesBackend(nro_page){
    sendAjax({
        url: "find_backend_channels/",
        data: {"busqueda":"","page":nro_page},
        success: function(data) {
            $("#backend").html(data);           
        }
    });
}

function borrar_canal(channel_id){
	sendAjax({
		url: "delete_channel/",
		data: {"channel_id":channel_id},
		success: function() {
                    buscarCanalesBackend(1, "");
		}
	});
}

//=====================================================================
//	Player
//=====================================================================

var player_curChannelId;
function setChannelSource(c_id,channel_name,channel_dsc){
	var url = "streaming_url/"+c_id;
	sendAjax({
		url: url,
		success: function(resp) {
			if(resp.ok){
				cleanPlayer();
				goalbit.playlist.add("gbtp://"+resp.url);
				$("#pchannel_dsc").text(channel_dsc);
				player_curChannelId = c_id;
				init_player(channel_name);
			}else{
				msg(resp.msg,'error');
			}
		}
	});
}

function markOfensiveChannel2(){
	var motivo = $.trim($("#txta_ofende").val());
	if(motivo==""){
		msg("Tienes que decir porque te ofende!",'error');
	}else{
		sendAjax({
			url: "channel_logic/mark_ofensive_channel/",
			data:{channel_id:player_curChannelId,comment:motivo},
			success: function(resp) {
				if(resp.ok){
					$("#div_ofende").jqmHide();
					msg(resp.msg);
				}else{
					msg(resp.msg,'error');
				}
				
			}
		});
	}
}

function markOfensiveChannel(){
	$("#div_ofende").jqmShow();
}

var state_label_content="";
function stop(){
	switch(state){
		case STATE_BROADCASTER:
			goalbit.playlist.broadcast_stop();
			break;
		case STATE_LOCAL_PLAYER:
			$("#btn_player_play").removeClass('pause').addClass('play');
			goalbit.playlist.stop();
			break;
		default:
			goalbit.playlist.stop();
	}
	if(!goalbit.playlist.isPlaying){
		if(state_label_content!=""){
			$("#state_label").text(state_label_content);
		}
		enableControls();
		time_play(false);
	}else{
		msg("No fue posible detener",'error');
	}
}

function setplayListSelected(ix){
    slider_set = false;
    if(play_list_items.length>0){
		selected_item = (ix<0)? (play_list_items.length-1):(ix%play_list_items.length);
		goalbit.playlist.stop();
		goalbit.playlist.playItem(selected_item);
		$("#btn_player_play").removeClass('play').addClass('pause');
		$("li.selected_item").removeClass("selected_item");
		$("#playlist_ul li.play_list_item:eq("+selected_item+")").addClass("selected_item");
    }
}

function play(){
	if(state==STATE_LOCAL_PLAYER){
		if (play_list_items.length>0){
			var input_state = goalbit.input.state;
			if(input_state!=INPUT_STATE_PLAYING && input_state!=INPUT_STATE_PAUSED){
				disableControls(["#btn_player_stop","#btn_player_play"]);
				cleanPlayer();
				for(var i=0;i<play_list_items.length;i++){
					addItemPlayer(play_list_items[i].mrl);
				}
				selected_item = getItemIndex($(".selected_item").attr("item"));
				if(selected_item<0){
					selected_item = 0;
					$("#playlist_ul li.play_list_item:first").addClass("selected_item");
				}
				goalbit.playlist.playItem(selected_item);
				$("#btn_player_play").removeClass('play').addClass('pause');
				time_play(true);
			}else{
				goalbit.playlist.togglePause();
				if(goalbit.playlist.isPlaying){
					$("#btn_player_play").removeClass('play').addClass('pause');
				}else{
					$("#btn_player_play").removeClass('pause').addClass('play');
				}
			}
		}
	}else{
		if(state==STATE_BROADCASTER){
			goalbit.playlist.broadcast_play();
			disableControls(["#btn_player_stop"]);
			state_label_content = $("#state_label").text();
			$("#state_label").text("Trasmitiendo...");
		}else{
			goalbit.playlist.play();
			disableControls(["#btn_player_stop"]);
			state_label_content = $("#state_label").text();
			$("#state_label").text("Reproduciendo...");
		}
	}
}

//=====================================================================
//	Local Player
//=====================================================================

function updatePlayerSlider(value,max){
    if(max<1)return;
	var step = 1/max;
    if(slider_set){
        $( "#slider" ).slider("value",value);
    }else{
        slider_set = true;
        $('#slider').slider({
            range: "min",
            value: value,
            min: 0,
            step:step,
            max: 1,
            slide: function( event, ui ) {
				goalbit.input.position = ui.value;
            }
        });
        $("#slider").slider({disabled: false});
    }
}
function getMinsSegs(milis){
    milis = milis/1000;
    var s = Math.floor(milis%60);
    var m = Math.floor((milis-s)/60);
	if(m<60){
		return (m<10 ? ("0"+m):m)+":"+(s<10 ? ("0"+s):s);
	}
	var h = Math.round(m/60);
	m = Math.floor(m%60);
	return (h<10 ? ("0"+h):h)+":"+(m<10 ? ("0"+m):m)+":"+(s<10 ? ("0"+s):s);
}

var timer,timer_running=false,input_time=1,slider_set;
function time_play2(){
    input_time = goalbit.input.time;
    input_length = goalbit.input.length;
    if((input_length > 0) && (input_length - input_time < 1000) && !goalbit.isPlaying && goalbit.input.state!=INPUT_STATE_PAUSED){
        next();
    }else{
        $("#state_label").text(getMinsSegs(input_time)+"/"+getMinsSegs(input_length));
        updatePlayerSlider(goalbit.input.position,input_length);
    }
	timer = setTimeout("time_play2()",1000);
}
function time_play(start){
    if(timer_running!=start){
        if(start){
            state_label_content = $("#state_label").text();
            slider_set=false;
            time_play2();
        }else{
            $("#state_label").text(state_label_content);
            clearTimeout(timer);
            $("#slider").slider({disabled: true, value:0});
        }
        timer_running=start;
    }
}

function next(){
    setplayListSelected(selected_item+1);
}

function prev(){
    setplayListSelected(selected_item-1);
}

function getItemIndex(item_id){
    for(var i=play_list_items.length-1;i>=0;i--)
        if(play_list_items[i].id==item_id)
            return i;
	return -1;
}

function delPlaylistItem(item_del){
    var $item = $(item_del).parent();
    var item_id = $item.attr("item");
    //Estoy seguro de existe en la playlist
	play_list_items.splice(getItemIndex(item_id), 1);
	$item.remove();
	if(play_list_items.length==0){
		$("#playlist .instructions").fadeIn("slow");
		$("#play_btn").removeClass("enable");
	}
}

function select_item(item_sel){
	setplayListSelected(getItemIndex($(item_sel).attr("item")));
}

function addPlaylistItem(){
	var $ul = $("#playlist_ul");
    if(play_list_items.length==0){
        $ul.find(".instructions").hide();
    }
    var item = new Object();
    item.id = id_incrementer++;
    item.label_type = "::";
    item.mrl = "file://" + file_path;
    item.label = file_name;
    if(item.label.length>40){
        item.label = item.label.substr(0,25)+"...";
    }
	var cur_clases = "play_list_item ui-corner-all";
	if(play_list_items.length==selected_item)
		cur_clases+=" selected_item";
    var li =
    "<li class='"+cur_clases+"' onclick='select_item(this);' item='"+ item.id +"'>"
        +"<span style='width:5em;margin: 0 1em;'><b>"+ item.label_type +"</b></span>"
        + item.label
		+ "<img src='"+base_url+"images/false.png' class='del_item_playlist' title='sacar' onclick='delPlaylistItem(this);'>"
    +"</li>";
    $ul.append(li);
	play_list_items.push(item);
    if(play_list_items.length==1){
        $("#play_btn").addClass("enable");
    }
}

function getFormatedFiles(path){
	try{
		return eval(goalbit.fileManager.ls(path));
	}catch(ex){
		msg("Error: "+ex,'error');
		return [];
	}
}

function browse_folder(){
	$("#choose_file").jqmShow();
}

var cur_folder="";
function curFolderListener(path){
    cur_folder = path;
    $("#spnCurFolder").html(cur_folder.length>30 ? ("..."+cur_folder.substr(cur_folder.length-30)):cur_folder);
}

function getFileChooserFilter(){
	var exts = $("#choose_fileExtension").val().replace(/[\s\t]/gi, "").replace(/,/gi,"|");
    return regex = exts!="" ? eval('/\\.('+exts+')$/i') : (/.*/);
}

function emptyPlayList(){
    $("#playlist_ul .play_list_item").remove();
    play_list_items.splice(0, play_list_items.length);
}

function end_browse_folder(){
	//Se actualiza la preferencia de usuario
	if(cur_folder!=""){
		AddFolderPlayList();
		sendAjax({
			url: "setUserPreferences",
			data: {name:'PLAYLIST_PATH',value:cur_folder},
			success: function(resp) {}
		});
	}
	$("#choose_file").jqmHide();
}

function fileChooserManager(){
	setModal("choose_file",'Carpeta: <span id="spnCurFolder"></span>');
	$('#files_chooser').fileTree(
		{root: "/", jsonProvider: getFormatedFiles, filterProvider: getFileChooserFilter, curFolderListener:curFolderListener},
		function(fileP, fileN) {
			file_path = fileP.substr(0, fileP.length-1);//para sacar la barra
			file_name = fileN;
			addPlaylistItem();
			$('#location_data_folder').val("Lista armada");
			$("#choose_file").jqmHide();
		}
	);
}

function AddFolderPlayList(){
	emptyPlayList();
	selected_item = 0;
	$('#location_data_folder').val(cur_folder);
	var arr = getFormatedFiles(cur_folder);
    var regex = getFileChooserFilter();
	
    for(var i=0;i<arr.length;i++){
        if(arr[i].is_dir == 0 && regex.test(arr[i].file_name)){
			file_name = arr[i].file_name;
            file_path = cur_folder+"/"+file_name;
            addPlaylistItem();
        }
	}
	if(play_list_items.length==0){
		$("#playlist_ul .instructions").fadeIn("slow");
	}
}

